package com.gxlu.ms.server.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * jredis config
 * @author lhc
 * @date 2018/2/19
 */
@Configuration
public class RedisConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class);

    @Value("${spring.profiles.active}")
    private String profile = "dev" ;

    /**
     * 日常环境中以不连 redis ，测试和线上环境，连redis
     * @param config
     * @param host
     * @param port
     * @param timeout
     * @param passowrd
     * @param database
     * @return
     */
    @Bean(name= "jedis.pool")
    @Autowired
    public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
                               @Value("${jedis.pool.host}")String host,
                               @Value("${jedis.pool.port}")int port,
                               @Value("${jedis.pool.config.timeout}")int timeout,
                               @Value("${jedis.pool.config.password}")String passowrd,
                               @Value("${jedis.pool.config.database}")int database) {
        try{
            JedisPool jedisPool =  new JedisPool(config, host, port,timeout,passowrd,database);
            return jedisPool ;
        }catch (Throwable e){
            logger.error("RedisConfiguration---init JedisPool is fail,current profile :"+profile,e);

            return  null ;
        }
    }

    @Bean(name= "jedis.pool.config")
    public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal,
                                            @Value("${jedis.pool.config.maxIdle}")int maxIdle,
                                            @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) {
        JedisPoolConfig config = new JedisPoolConfig();
        //设置最大连接数
        config.setMaxTotal(maxTotal);
        //最大空闲连接数
        config.setMaxIdle(maxIdle);
        //获取Jedis连接的最大等待时间 30 s
        config.setMaxWaitMillis(maxWaitMillis);
        //在获取Jedis连接时，自动检验连接是否可用
        config.setTestOnBorrow(true);
        //在将连接放回池中前，自动检验连接是否有效
        config.setTestOnReturn(true);
        //自动测试池中的空闲连接是否都是可用连接
        config.setTestWhileIdle(true);
        return config;
    }

}